package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.Question;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.dto.RecommendUserDto;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.NearUserVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import com.tanhua.server.exeception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author SunSun
 * @date 2021/10/25
 */
@Service
public class TanhuaService {

    @DubboReference
    private UserLocationApi userLocationApi;
    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Value("${tanhua.default.recommend.users}")
    private String recommendUser;

    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private MessagesService messagesService;

    @DubboReference
    private VisitorsApi visitorsApi;

    public TodayBest todayBest() {

        Long userId = UserHolder.getUserId();

        RecommendUser recommendUser = recommendUserApi.queryWithMaxStore(userId);

        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(userId);
            recommendUser.setScore(99d);
        }

        UserInfo userInfo = userInfoApi.findByid(recommendUser.getUserId());

        TodayBest todayBest = new TodayBest();

        TodayBest best = todayBest.init(userInfo, recommendUser);

        return best;
    }

    public PageResult recommendation(RecommendUserDto dto) {

        Long userId = UserHolder.getUserId();

        PageResult pr = recommendUserApi.queryRecommendationList(dto.getPage(), dto.getPagesize(), userId);

        List<RecommendUser> items = (List<RecommendUser>) pr.getItems();

        if (CollUtil.isEmpty(items)) {
            return pr;
        }

        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);

        UserInfo userInfo=new UserInfo();
        userInfo.setAge(dto.getAge());
        userInfo.setGender(dto.getGender());

        Map<Long, UserInfo> byIds = userInfoApi.findByIds(userIds, userInfo);

        List<TodayBest> list = new ArrayList<>();
        for (RecommendUser item : items) {
            UserInfo info = byIds.get(item.getUserId());
            if(info!=null){
                TodayBest vo = TodayBest.init(info,item);
                list.add(vo);
            }

        }
        pr.setItems(list);
        return  pr;
    }

    /**
     * 查看佳人详情
     * @param userId
     * @return
     */
    public TodayBest personalInfo(Long userId) {
        UserInfo info = userInfoApi.findByid(userId);
        RecommendUser re=recommendUserApi.queryByUserId(userId,UserHolder.getUserId());

        //保存访客信息
        Visitors visitors=new Visitors();
        visitors.setUserId(userId);
        visitors.setVisitorUserId(UserHolder.getUserId());
        visitors.setFrom("首页");
        visitors.setScore(re.getScore());
        visitors.setDate(System.currentTimeMillis());
        visitors.setVisitDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        visitorsApi.save(visitors);

        TodayBest todayBest = TodayBest.init(info, re);
        return todayBest;
    }

    public String strangerQuestions(Long userId) {
        Question question = questionApi.findUserid(userId);
        return question==null?"你喜欢内卷吗":question.getTxt();
    }

    public void replyQuestions(Long userId, String reply) {
        Long currentUserId = UserHolder.getUserId();
        UserInfo userInfo = userInfoApi.findByid(currentUserId);

        Map map=new HashMap();
        map.put("userId",currentUserId);
        map.put("huanXinId",Constants.HX_USER_PREFIX+currentUserId);
        map.put("nickname",userInfo.getNickname());
        map.put("strangerQuestion",strangerQuestions(userId));
        map.put("reply",reply);
        String text = JSON.toJSONString(map);

        Boolean aBoolean = huanXinTemplate.sendMsg(Constants.HX_USER_PREFIX + userId, text);

        if(!aBoolean){
            throw  new BusinessException(ErrorResult.error());
        }

    }

    public List<TodayBest> queryCardsList() {
        List<RecommendUser> list=recommendUserApi.queryCardsList(UserHolder.getUserId(),10);

        if(CollUtil.isEmpty(list)){
            list=new ArrayList<>();
            String[] userIds = recommendUser.split(",");
            for (String userId : userIds) {
                RecommendUser recommendUser=new RecommendUser();
                recommendUser.setScore(RandomUtil.randomDouble(60,90));
                recommendUser.setUserId(Convert.toLong(userId));
                recommendUser.setToUserId(UserHolder.getUserId());
                list.add(recommendUser);
            }
        }
        List<Long> userId = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userId, null);
        List<TodayBest> vos =new ArrayList<>();
        for (RecommendUser user : list) {
            UserInfo userInfo = map.get(user.getUserId());
            if(userInfo!=null){
                TodayBest todayBest = TodayBest.init(userInfo, user);
                vos.add(todayBest);
            }
        }
        return vos;
    }

    public void likeUser(Long likeUserId) {
        boolean save=userLikeApi.saveOrUpdate(UserHolder.getUserId(),likeUserId,true);

        if (!save){
            throw new BusinessException(ErrorResult.error());
        }
        redisTemplate.opsForSet().remove(Constants.USER_NOT_LIKE_KEY+UserHolder.getUserId(),likeUserId.toString());
        redisTemplate.opsForSet().add(Constants.USER_LIKE_KEY+UserHolder.getUserId(),likeUserId.toString());

        if(isLike(likeUserId,UserHolder.getUserId())){
            messagesService.contacts(likeUserId);
        }

    }
    public boolean isLike(Long userId,Long likeUserId){
        String key=Constants.USER_LIKE_KEY+userId;
        return  redisTemplate.opsForSet().isMember(key,likeUserId.toString());
    }

    public void notLikeUser(Long likeUserId) {
        boolean save=userLikeApi.saveOrUpdate(UserHolder.getUserId(),likeUserId,false);

        if (!save){
            throw new BusinessException(ErrorResult.error());
        }

        redisTemplate.opsForSet().add(Constants.USER_NOT_LIKE_KEY+UserHolder.getUserId(),likeUserId.toString());
        redisTemplate.opsForSet().remove(Constants.USER_LIKE_KEY+UserHolder.getUserId(),likeUserId.toString());
    }

    public List<NearUserVo> queryNearUser(String gender, String distance) {

        List<Long> userIds=userLocationApi.queryNearUser(UserHolder.getUserId(),Double.valueOf(distance));

        if(CollUtil.isEmpty(userIds)){
            return new ArrayList<>();
        }
        UserInfo userInfo=new UserInfo();
        userInfo.setGender(gender);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, userInfo);

        List<NearUserVo> list=new ArrayList<>();
        for (Long userId : userIds) {
            //排除当前用户

            if(userId .equals(UserHolder.getUserId()) ) {
                continue;
            }
            UserInfo info = map.get(userId);
            if(info!=null){
                NearUserVo vo = NearUserVo.init(info);
                list.add(vo);
            }
        }
        return list;
    }
}
//        List<TodayBest> list = new ArrayList<>();
//        for (RecommendUser item : items) {
//            Long recommendUserId = item.getUserId();
//            UserInfo byid = userInfoApi.findByid(recommendUserId);
//            if (byid != null) {
//                if (!StringUtils.isEmpty(dto.getGender()) && !dto.getGender().equals(byid.getGender())) {
//                    continue;
//                }
//                if (dto.getGender() != null && dto.getAge() < byid.getAge()) {
//                    continue;
//                }
//
//                TodayBest vo = TodayBest.init(byid, item);
//                list.add(vo);
//            }
//
//        }
//
//        pr.setItems(list);
//        return pr;

